package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"monitor_serve/config"
	"monitor_serve/mq"
	ossaliyun "monitor_serve/store/oss"
	"os"
)

func main() {
	fmt.Println("开始监听转移任务队列...")
	//发布消息，进行转移
	mq.StartConsume(
		config.RabbitMQ.TransOSSQueueName,
		"transfer_oss",
		ProcessTransfer)
}

// 转移
func ProcessTransfer(msg []byte) bool {
	//1.解析msg
	fmt.Println("ProcessTransfer")
	pubData := mq.TransferData{}
	err := json.Unmarshal(msg, &pubData)
	if err != nil {
		fmt.Println("Error unmarshalling message:", err)
		return false
	}
	fmt.Println(pubData)
	//2.根据临时存储文件路径，创建文件句柄
	filed, _ := os.Open(pubData.CurLocation)
	if err != nil {
		fmt.Println("Error opening file:", err)
		return false
	}
	defer filed.Close()
	fmt.Println("filed:", filed)
	//3.通过文件句柄将文件内容读出来并且上传到oss

	err = ossaliyun.GetBucket().PutObject(
		pubData.DestLocation,
		bufio.NewReader(filed),
	)
	if err != nil {
		fmt.Println(err)
		return false
	}
	fmt.Println("pubData.FileHash:", pubData.FileHash)
	fmt.Println("pubData.DestLocation:", pubData.DestLocation)
	//4.更新文件的存储路径到文件表,这里有问题，明白了这里我用数据库了，但是我的数据库没连接。没有初始化
	//err = service.ServiceGroupApp.FileService.UpdateFileInfoLocation(pubData.FileHash, pubData.DestLocation)
	//if err != nil {
	//	fmt.Println(err)
	//	return false
	//}
	return true
}
